//
//  HttpClient.m
//  esan_cloud_core
//
//  Created by TianMing on 2018/9/20.
//  Copyright © 2018年 esandinfo. All rights reserved.
//

#import "HttpClient.h"
// 此类为了实现跟业务服务器进行数据同步
@implementation HttpClient
{
    NSURL * _nsURL;
}

- (id) initWithNSURL:(NSURL *)nsURL
{
    self = [super init];
    if (self) {
        
        _nsURL = nsURL;
    }
    
    return self;
}
/**
    * json请求方式，用于请求业务服务器
 */
- (void) requestSync:(NSString *)bodyString  clientCallback:(ClientCallback) clientCallback
{
    NSLog(@"bodyString = %@", bodyString);
    NSMutableURLRequest *nsMutableURLRequest = [NSMutableURLRequest requestWithURL:_nsURL
                                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                                   timeoutInterval:10];
    //POST请求
    [nsMutableURLRequest setHTTPMethod:@"POST"];
    //把bodyString转换为NSData数据
    NSData *bodyData =  [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    [nsMutableURLRequest setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [nsMutableURLRequest setValue:@"UTF-8" forHTTPHeaderField:@"Charset"];
    //body 数据
    [nsMutableURLRequest setHTTPBody:bodyData];
    //创建任务
    NSURLSessionDataTask * task = [[NSURLSession sharedSession] dataTaskWithRequest:nsMutableURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"%@",((NSHTTPURLResponse*)response).allHeaderFields);
            NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            NSLog(@"%@", error);
            NSString* resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            clientCallback(resultStr);
        }else{
            clientCallback(nil);
        }
    }];
    //开启网络任务
    [task resume];
}

/**
 * 获取当前时间戳
 * @return 返回时间戳的字符串，格式为 yyyyMMddHHmmssSSS
 */
- (NSString *)getTimeStampStr
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
   
    return dateStr;
}

/**
    application/x-www-form-urlencoded 请求方式用于请求阿里云
 */
// 为了方便把流程说清楚，这里用了同步方法，在接入的时候兼用用异步方式实现。
- (void) requestSync:(NSString *)bodyString appCode:(NSString *) appCode clientCallback:(ClientCallback) clientCallback
{
    
        
        NSMutableURLRequest *nsMutableURLRequest = [NSMutableURLRequest requestWithURL:_nsURL
                                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                                       timeoutInterval:10];
        //POST请求
        [nsMutableURLRequest setHTTPMethod:@"POST"];
        //把bodyString转换为NSData数据

        bodyString = [bodyString stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
        
        NSData *bodyData =  [bodyString dataUsingEncoding:NSUTF8StringEncoding];
        //请求头
        NSLog(@"%@", bodyString);
        [nsMutableURLRequest addValue:@"application/x-www-form-urlencoded ;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        //防重放
        [nsMutableURLRequest setValue:[self getTimeStampStr] forHTTPHeaderField:@"X-Ca-Nonce"];
        //APPCODE
        [nsMutableURLRequest setValue: [NSString stringWithFormat:@"APPCODE %@",appCode] forHTTPHeaderField:@"Authorization"];
    
//        [nsMutableURLRequest addValue:@"TEST" forHTTPHeaderField:@"X-Ca-Stage"];
        //body 数据
        [nsMutableURLRequest setHTTPBody:bodyData];
        //创建任务
        NSURLSessionDataTask * task = [[NSURLSession sharedSession] dataTaskWithRequest:nsMutableURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"%@",((NSHTTPURLResponse*)response).allHeaderFields);
                NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                NSLog(@"%@", error);
                NSString* resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                clientCallback(resultStr);
            }else{
                clientCallback(nil);
            }
        }];
        //开启网络任务
        [task resume];
}

@end
